package org.apache.cordova.engine;


import android.content.Context;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;

import org.apache.cordova.CordovaWebView;
import org.apache.cordova.CordovaWebViewImpl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


/**
 * Created by Kane on 2017/9/1.
 */


public class WebViewPool {

    private static final String DEMO_URL = "https://m.baidu.co";
    private static List<X5WebView> available = new ArrayList<>();

    private static final byte[] lock = new byte[]{};
    private static int maxSize = 4;

    private Context applicationContext;

    private WebViewPool(Context context) {
        this.applicationContext = context.getApplicationContext();

    }

    private static volatile WebViewPool instance = null;

    public static WebViewPool init(Context applicationContext) {
        if (instance == null) {
            synchronized (WebViewPool.class) {
                if (instance == null) {
                    instance = new WebViewPool(applicationContext);
                }
            }
        }
        return instance;
    }

    public static WebViewPool getInstance() {
        return instance;
    }

    /**
     * Webview 初始化
     * 最好放在application oncreate里
     * */
    public static void init() {
        for (int i = 0; i < maxSize; i++) {
            X5WebView webView = createWebview();
            available.add(webView);
        }
    }

    private static X5WebView createWebview() {
        X5WebView webView = new X5WebView(instance.applicationContext);
        webView.loadUrl("about:blank");
        return webView;
    }

    /**
     * 获取webview
     *
     * */
    public X5WebView getWebView() {

        synchronized (lock) {
            if (available.size() == 0) {
                init();
            }

            X5WebView webView;
            if (available.size() > 0) {
                webView = available.get(0);
                available.remove(0);

                available.add(createWebview());

                return webView;
            }
            return createWebview();
        }
    }

    /**
     * 回收webview ,解绑
     *@param webView 需要被回收的webview
     *
     * */
    public void removeWebView(ViewGroup view, X5WebView webView) {
        view.removeView(webView.getView());

        removeWebView(webView);
    }

    public void removeWebView(X5WebView webView) {

        synchronized (lock) {
//            String url = webView.getUrl();
            available.add(webView);

        }
    }
    /**
     * 设置webview池个数
     * @param size webview池个数
     * */
    public void setMaxPoolSize(int size) {
        synchronized (lock) {
            maxSize = size;
        }
    }

}
